#include "chatTask.h"
#include "session.h"
#include "common.h"
using json = nlohmann::json;

// 修改：添加外部互斥锁声明
extern std::mutex userMapMutex;
extern map<int, int> userMap;

/**
 * @brief 聊天任务处理线程函数
 */
void taskThread(int clientFd)
{
	try
	{
		printf("-------------------- new connect --------------------\n");		
        
        Session session(clientFd);
		json msg;
        
		while (1)
		{
			// 修改：先接收消息，再处理
			msg = session.recvMsg();			
            
			if (msg.at("cmd") == cmd_logout)
			{
				std::cout << "用户" << std::to_string(clientFd) << "下线" << std::endl;
                
                // 修改：添加线程安全保护
                {
                    std::lock_guard<std::mutex> lock(userMapMutex);
                    if(userMap.size() == 1)
                    {
                        userMap.erase(clientFd);
                        close(clientFd);
                        return ;
                    }
                    
                    if(userMap.find(clientFd) != userMap.end())
                    {
                        int account = userMap.at(clientFd);
                        
                        // 使用会话的数据库连接
                        Statement query(session.getDatabase(), "update user set online=0 where account=?");
                        query.bind(1, account);
                        query.exec();
                        
                        json message;
                        message["account"] = std::to_string(account);
                        message["cmd"] = "logout";  // 修正拼写错误

                        std::cout << "用户" << std::to_string(userMap.at(clientFd)) << "下线" << std::endl;
                        userMap.erase(clientFd);
                    }
                }
                
				close(clientFd);
				return ;
			}
            
            // 修改：在这里处理消息而不是在recvMsg内部
            session.handleMsg(msg);
		}
	}
	catch (std::exception& e)
	{
		std::cerr << "Exception caught: " << e.what() << std::endl;
        
        // 修改：添加线程安全保护
        {
            std::lock_guard<std::mutex> lock(userMapMutex);
            userMap.erase(clientFd);
        }
        
        close(clientFd);
        return ;
	}
}